<?php declare(strict_types=1);


namespace App\Controller;

use App\Common\Response;
use App\Exception\DaoException;
use App\Model\EventInfo;
use App\Service\HashPassWordService;
use App\Service\JwtService;
use App\Service\StudentService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use LogicException;
use Swoole\Exception;
use App\Middleware\EncryptionMiddleware;
use App\Middleware\AuthMiddleware;


/**
 * @Controller()
 */
class StudentController extends AbstractController
{

    /**
     * @Inject()
     * @var StudentService
     */
    private StudentService $studentService;

    /**
     * @Inject()
     * @var HashPassWordService
     */
    private HashPassWordService $hashPassService;
    /**
     * @Inject()
     * @var JwtService
     */
    private JwtService $JwtService;


    /**
     * @RequestMapping(path="/student/login",methods="post")
     * * @Middlewares({
     *   @Middleware(EncryptionMiddleware::class)
     * })
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function login(): \Psr\Http\Message\ResponseInterface
    {
        try{
            $params = $this->getParams();
            // 查询用户是否存在
            $student = $this->studentService->findCheck($params['stu_num'] ?? '');
            // 密码校验
            $this->hashPassService->verifyCast($params['password']??'', $student->sale, $student->password);
            // token的数据
            $userData = [
                'id' => $student->id,
                'stu_num' => $student->stu_num,
                'nick_name' => $student->nick_name,
                'class' => $student->class,
                'grade' => $student->grade,
                'login_ip' => $student->login_ip,
                'is_admin' => $student->is_admin,
                'status' => $student->status,
                'created_at' => $student->created_at,
            ];
            // 生成token
            $token = $this->JwtService->genToken($userData);
            unset($userData['id'],$userData['login_ip']);
            return $this->response->json(Response::success(compact('token','userData')));
        }catch (Exception $e) {
            return $this->response->json(Response::fail($e->getMessage(),$e->getCode()));
        }
    }

    /**
     *  修改密码
     */
    public function editPassword(): \Psr\Http\Message\ResponseInterface
    {
        $params = $this->getParams();
        $newPwd = $params['new_password'] ?? '';
        $validatePwd = $params['again_password'] ?? '';
        if(strlen($params['new_password']) < 6) {
            return $this->response->json(Response::fail('密码长度不能低于6位'));
        }
        if(!$newPwd){
            return $this->response->json(Response::fail('新密码不能为空'));
        }
        if($newPwd !== $validatePwd) {
            return $this->response->json(Response::fail('两次密码输入不一致'));
        }
        $user = $this->getUser();
        $student = $this->studentService->find($user['stu_num']);
        $hashPasswd = $this->hashPassService->genPassWord($newPwd, $student->sale);
        $this->studentService->editPassword($student, $hashPasswd);
        return $this->response->json(Response::success('修改成功'));
    }


    /**
     * 学生个人提交的作业
     * @RequestMapping(path="/student/event/list",methods="get")
     * @Middlewares({
     *   @Middleware(AuthMiddleware::class),
     *   @Middleware(EncryptionMiddleware::class)
     * })
     */
    public function eventList()
    {
        $user = $this->getUser();
        $params = $this->getParams();
        return EventInfo::query()->where('submitter_id', $user['id'])
            ->with('files')
            ->select(['event_name','submitter','remark','created_at', 'id'])
            ->paginate(20, ['*'], 'page', $params['page'] ?? 1);
    }


    /**
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function addStudent()
    {
        try{
            $params = $this->getParams();
            var_dump($params);
            $this->check($params['stu_num'] ?? '','学号不能为空');
            $this->check($params['nick_name'] ?? '','昵称不能为空');
            $this->check($params['password'] ?? '','密码不能为空');
            $password = $params['password'];
            $uInfo = [
                'stu_num' => $params['stu_num'],
                'nick_name' => $params['nick_name'],
                'class' => 'a21',
                'grade' => 3,
                'sale' => 'p3n5432',
                'status' => 1,
                'is_admin' => 0
            ];
            $pwd = $this->hashPassService->genPassWord($password, $uInfo['sale']);
            $uInfo['password'] = $pwd;
            $student = $this->studentService->add($uInfo);
            $displayData = [
                'id' => $student->id,
                'stu_num' => $student->stu_num,
                'nick_name' => $student->nick_name,
                'class' => $student->class,
                'grade' => $student->grade,
                'login_ip' => $student->login_ip,
                'is_admin' => $student->is_admin,
                'status' => $student->status,
                'created_at' => $student->created_at,
            ];
            return  $this->response->json(Response::success($displayData,'添加成功，学号: '. $student->stu_num));
        }catch (LogicException | DaoException $e) {
            return $this->response->json(Response::fail($e->getMessage()));
        } catch (\Exception $e) {
            return $this->response->json(Response::fail('Exception：'.$e->getMessage()));
        }
    }




}
